package com.lsy.service.impl;

import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.lsy.entity.User;
import com.lsy.entity.UserCustom;
import com.lsy.entity.UserQueryVo;
import com.lsy.mapper.interf.UserMapper;
import com.lsy.mapper.interf.UserMapperCustom;
import com.lsy.service.interf.UserService;

/**
 * user的业务实现类
 * 
 * @author ZhangWeiQiang
 *
 */
@Service
@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class UserServiceImpl implements UserService {

	// 自动注入userMapper
	@Autowired
	private UserMapper userMapper;
	// 自动注入UserMapperCustom
	@Autowired
	private UserMapperCustom userMapperCustom;

	public boolean save(User object) throws RuntimeException {
		// boolean result = false;
		// if (userMapper.insert(object) > 0) {
		// result = true;
		// }
		return true;

	}

	// 添加用户
	public void AddUser(UserCustom userCustom) throws Exception {
		// 进行业务校验，在service中要对关键参数进行校验
		// 校验id是否为空
		userMapper.insertSelective(userCustom);
	}

	// 获取用户列表
	public List<UserCustom> findUserList(UserQueryVo userQueryVo) throws Exception {

		return userMapperCustom.findUserList(userQueryVo);
	}

	// 通过Id查找用户信息
	public UserCustom findUserById(Integer id) throws Exception {
		// TODO Auto-generated method stub
		User user = userMapper.selectByPrimaryKey(id);
		// 可做扩展
		UserCustom userCustom = new UserCustom();
		// 将user内容拷贝到usercustom中
		BeanUtils.copyProperties(user, userCustom);
		return userCustom;
	}

	// 更新用户信息
	public void UpdateUserInfo(Integer id, UserCustom userCustom) throws Exception {
		// 进行业务校验，在service中要对关键参数进行校验
		// 校验id是否为空

		// 更新用户信息
		userCustom.setUserid(id);
		userMapper.updateByPrimaryKeySelective(userCustom);
	}

	public void deleteUser(Integer id) throws Exception {
		// TODO Auto-generated method stub
		userMapper.deleteByPrimaryKey(id);

	}

	//用户登录
	public User login(String phone, String password) throws Exception {
		if (phone == null || phone.equals("")) {
			return null;
		}
		User user = userMapper.selectByPhone(phone);
		if (user == null || !user.getUpassword().equals(password)) {
			return null;
		}
		user.setUpassword("");
		return user;
	}

	//获取用户余额
	public long findUserMoney(int userId) throws Exception {
		return userMapperCustom.findUserMoney(userId);
	}
	//更新用户余额
	public boolean updateMoney(long money, int userId) throws Exception {
		boolean result = false;
		if (userMapperCustom.updateMoney(money, userId) > 0) {
			result = true;
		}
		return result;
	}

}
